package com.ydev.lazywallet.gui;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import com.ydev.lazywallet.R;

import org.Constants;
import org.DataTransfer;
import org.Global;
import org.ydClipBoardManager;
import org.json.JSONException;
import org.json.JSONObject;

import CustomUI.HomeTableCell;
import CustomUI.Input_Dialog;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.Locale;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class Home extends Activity {
	
	LinearLayout llMain;
	
	ClipboardManager mClipboard;
	
	JSONObject data;
	
	
	 private String[] mPlanetTitles;
	    private DrawerLayout mDrawerLayout;
	    private ListView mDrawerList;
	    
	    private CharSequence mDrawerTitle;
	    private CharSequence mTitle;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		
		mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		
		
		Global.getDeviceID(getApplicationContext());
		
		llMain=(LinearLayout)findViewById(R.id.llTableMain);
		
		mClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
			loadCells();
	}
	
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
	    @Override
	    public void onItemClick(AdapterView parent, View view, int position, long id) {
	        selectItem(position);
	    }
	}

	/** Swaps fragments in the main content view */
	private void selectItem(int position) {
	    // Create a new fragment and specify the planet to show based on position
	    Fragment fragment = new PlanetFragment();
	    Bundle args = new Bundle();
	    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
	    fragment.setArguments(args);

	    // Insert the fragment by replacing any existing fragment
	    FragmentManager fragmentManager = getFragmentManager();
	    fragmentManager.beginTransaction()
	                   .replace(R.id.content_frame, fragment)
	                   .commit();

	    // Highlight the selected item, update the title, and close the drawer
	    mDrawerList.setItemChecked(position, true);
	    setTitle(mPlanetTitles[position]);
	    mDrawerLayout.closeDrawer(mDrawerList);
	}

	@Override
	public void setTitle(CharSequence title) {
	    mTitle = title;
	    getActionBar().setTitle(mTitle);
	}
	
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
	
	public void AddClicked(View v){
		Input_Dialog iD=new Input_Dialog(this, 0);
		iD.show();
	}

    public void BackUpClicked(View view){
    	 new MyAsyncTask().execute();
    }
	
	public void ClearClipBoard(View v){
		ydClipBoardManager.clearClipBoard();
	}
	
	public void addObject(String s){
		try {
			JSONObject d;
			if(Global.sampleData.length()<=0)
				d=new JSONObject();
			else
				d=new JSONObject(Global.sampleData);
			
			d.put(s,new JSONObject());
			Global.sampleData=d.toString();
			Global.saveData();
			loadCells();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void loadCells(){
		if(Global.sampleData.length()<=0){
			return;
		}
		try {
			data=new JSONObject(Global.sampleData);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Iterator<String> iter = data.keys();
		HomeTableCell htc;
		
		llMain.removeAllViews();
		
	    while (iter.hasNext()) {
	        String key = iter.next();
	        try {
	            Object value = data.get(key);
	            htc=new HomeTableCell(this, getApplicationContext());
	            htc.setTitle(key.toString());
	            llMain.addView(htc);
	        } catch (JSONException e) {
	            // Something went wrong!
	        }
	    }
	}
	
	private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
		  @Override
		  protected Double doInBackground(String... params) {
			// TODO Auto-generated method stub
			  try {
				DataTransfer.sendBackUp();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		        return null;
		  }
		 
		  protected void onPostExecute(Double result){
			
			Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
		  } 
		  
		  protected void onProgressUpdate(Integer... progress){
		  
		  }
		}
}
